const BaseController = require("./base");
const jwt = require("jsonwebtoken");
const md5Password = require("../utils/password-handler");

class AuthController extends BaseController {
	async login() {
		const { ctx } = this;
		const rule = {
			username: "string",
			password: "string"
		};
		ctx.validate(rule, ctx.request.body);
		const data = ctx.request.body;
		data.password = md5Password(data.password);
		const [user] = await this.app.mysql.select("user", {
			where: {
				username: data.username
			}
		});

		if (!user) {
			this.error(400, "用户名不存在");
		} else if (user.password !== data.password) {
			this.error(400, "密码错误");
		} else {
			const expires_in = 60 * 60 * 24;
			const token = jwt.sign(data, this.config.PRIVATE_KEY, {
				expiresIn: expires_in, //过期时间
				algorithm: "RS256" //加密算法
			});
			this.ctx.body = {
				code: 200,
				message: "登录成功",
				token,
				expires_in
			};
		}
	}
}

module.exports = AuthController;
